<template>
	<view class="content">

		<view class="chartContainer">
			<self-navbar type='reLaunch' backPath="/pages/consultant/consultant" title="在线咨询"></self-navbar>
			<global-notify :groupId='chartGroup.groupId'></global-notify>
			<view class="chatInfo" style="flex-grow: 1; ">
				<scroll-view class="scroll-view" scroll-y scroll-with-animation :scroll-top="top">
					<view v-for="(item, index) in dataList" class="chat-item">
						<template v-if="item.sendUserId == 'system_notice'">
							<text class="chat-time">
								{{formatTime(item.whenCreated, "YYYY年MM月DD日 HH:mm")}}
							</text>
							<view class="chat-tipInfo">
								<view class="tip">{{item.messageInfo.content}}</view>
							</view>
						</template>
						<template v-else>
							<text class="chat-time" v-if="index%10 ==0">
								{{formatTime(item.whenCreated, "HH:mm")}}
							</text>
							<view :class="{'chat-container':true,'chat-location-me':isMe(item.sendUserId)}">
								<view class="chat-icon-container">
									<u-avatar class="chat-icon" :src="userInfo(item.sendUserId, 'avatar') || getDefault(item.sendUserId)"
										mode="aspectFill" />
								</view>
								<view class="chat-content-container">
									<text :class="{'chat-user-name':true,'chat-location-me':isMe(item.sendUserId)}">
										<template v-if="userInfo(item.sendUserId, 'consultant')">
											{{userInfo(item.sendUserId, 'name') |desensitizedName}}
										</template>
										<template v-else>{{userInfo(item.sendUserId, 'name')}}</template>
									</text>
									<view class="chat-text-container-super"
										:style="[{justifyContent:isMe(item.sendUserId)?'flex-end':'flex-start'}]">
										<view :class="{'chat-text-container':true,'chat-text-container-me':isMe(item.sendUserId)}">
											<view :class="{'chat-text':true,'chat-text-me':isMe(item.sendUserId)}">
												<template v-if="item.messageType == 'ImgMsg'">
													<!-- <img style="max-width: 100%;max-height: 100%;" :src="item.messageInfo.imageUri" /> -->
													<u--image @click='previewImg(item)' mode='scaleToFill' webp :src="item.messageInfo.imageUri">
														<template v-slot:loading>
															<u-loading-icon color="red"></u-loading-icon>
														</template>
														<view slot="error" style="font-size: 24rpx;">加载失败</view>
													</u--image>
												</template>
												<template v-else-if="item.messageType == 'GIFMsg'">
													<u--image @click='previewImg(item)' webp :src="item.messageInfo.remoteUrl">
														<template v-slot:loading>
															<u-loading-icon color="red"></u-loading-icon>
														</template>
														<view slot="error" style="font-size: 24rpx;">加载失败</view>
													</u--image>
												</template>
												<template v-else-if="item.messageType == 'SightMsg'">
													<video @error="videoErrorCallback" @click='previewImg(item)' object-fit="fill"
														:autoplay="false" :src="item.messageInfo.sightUrl" controls></video>
												</template>
												<template v-else-if="item.messageType == 'HQVCMsg'">
													<audio object-fit="fill" :autoplay="false" :src="item.messageInfo.sightUrl" controls></audio>
												</template>

												<template v-else>
													<template v-if="item.messageExtra == 'share'">
														<view v-if="item.messageInfo.params && Object.keys(item.messageInfo.params).length > 0"
															@click='viewShare(item.messageInfo.params)' class="shareCard">
															<view class="shareTitle">
																【{{item.messageInfo.params.typeLabel || '未分类'}}】{{item.messageInfo.params.name}}
															</view>
															<view class="shareCardContent">
																<u--image v-if="item.messageInfo.params.cover" customStyle="margin-right: 10px;"
																	mode='scaleToFill' :radius='10' height='100px' width='80px'
																	:src="item.messageInfo.params.cover">
																	<view slot="error" style="font-size: 24rpx;">加载失败</view>
																</u--image>
																<view class="shareContent">
																	<view class="shareContentRemark">摘要：{{item.messageInfo.params.remark || '--'}}</view>
																	<view class="shareContentBaseItem">来源：{{item.messageInfo.params.source || '--'}}
																	</view>
																	<view class="shareContentBaseItem">作者：{{item.messageInfo.params.author || '--'}}
																	</view>
																</view>
															</view>
														</view>
														<view v-else>无效的分享链接</view>
													</template>
													<view v-else>{{item.messageInfo.content}}</view>
												</template>
											</view>
										</view>
									</view>
								</view>
							</view>
						</template>
					</view>
				</scroll-view>
			</view>
			<view class="chat-input-bar-container" ref="inputBar" v-if="!disconnectIM && !consultationFinished">
				<view class="chat-input-bar">
					<view class="chat-input-container">
						<!-- :adjust-position="false"必须设置，防止键盘弹窗自动上顶，交由z-paging内部处理 -->
						<u--textarea autoHeight :adjust-position="false" @focus="messageFocus" @blur="messageBlur"
							class="chat-input" v-model="msg" confirmType="send" placeholder="请输入内容"
							@confirm="sendMessage"></u--textarea>
					</view>
					<!-- 表情图标（如果不需要切换表情面板则不用写） -->
					<view class="btn-container">
						<image class="emoji-img" :src="`/static/images/im/${emojiType || 'emoji'}.png`" @click="emojiChange">
						</image>
						<image class="emoji-img" :src="`/static/images/im/plus.png`" @click="moreAction">
						</image>
					</view>

					<view v-if="showSendBtn" class="chat-input-send" @click="sendMessage">
						<text class="chat-input-send-text">发送</text>
					</view>
				</view>
				<!--  表情面板，这里使用height控制隐藏显示是为了有高度变化的动画效果（如果不需要切换表情面板则不用写） -->
				<view class="action-panel-container"
					:style="[{height: showMoreAction || emojiType === 'keyboard' ? '400rpx' : '0px'}]">
					<scroll-view scroll-y style="height: 100%;flex: 1;">
						<view class="action-panel">
							<template v-if="showMoreAction">
								<!-- 操作面板 -->
								<view class="action-item" v-for="(action, index) in moreActions" :key="index">
									<view class="action-item-centent" @click="actionClick(action)">
										<u-icon size='28' :name="action.icon"></u-icon>
									</view>
									<view class="action-item-label">{{action.label}}</view>
								</view>
							</template>
							<template v-else-if="emojiType === 'keyboard'">
								<!-- 表情面板 -->
								<text class="action-panel-text" v-for="(item, index) in emojisArr" :key="index"
									@click="emojiClick(item)">
									{{item}}
								</text>
							</template>
						</view>
					</scroll-view>
				</view>

			</view>
		</view>

		<u-popup :show="showQuickReplie" title="快捷回复" closeable :round="10" :safeAreaInsetBottom='true' mode="bottom"
			@close="showQuickReplie=false">
			<view style="padding-top: 44px; max-height: 66vh; ">
				<view style="box-sizing: border-box; padding:10px;overflow-y: auto;">
					<view @click="selectQuickReplie(quickReplie)" class="flex"
						style="justify-content: space-between; line-height: 2.4rem; padding: ; border-bottom: 1px solid #f2f2f2"
						v-for="(quickReplie, index) in quickReplieList" :key="index">
						{{quickReplie.message}}
					</view>
				</view>
			</view>
		</u-popup>

		<u-popup :show="showSp" title="业务类型" closeable :round="10" :safeAreaInsetBottom='true' mode="bottom"
			@close="closeSp">
			<view style="padding-top: 44px; max-height: 66vh; display: flex;flex-direction: column;overflow: hidden;">
				<view style="box-sizing: border-box;flex-grow: 1;padding:10px;overflow-y: auto;">
					<self-cascade-select v-if="showSp" :loading="loadingSp" @change='changeData' :options='spData'
						:values='chartGroup.dicSpecialtyIds'></self-cascade-select>
				</view>
				<!-- 	<view class="flex" style="box-sizing: border-box;height: max-content; min-height: max-content;padding: 10px;">
					<u-button @click="closeSp" size="small" customStyle="margin-right: 1rem">取消</u-button>
					<u-button @click="submitSp" size="small" type="primary">确定</u-button>
				</view> -->
			</view>
		</u-popup>

		<u-popup :show="showTags" title="咨询标签" closeable :round="10" :safeAreaInsetBottom='true' mode="bottom"
			@close="closedTag">
			<view style="padding-top: 44px; max-height: 66vh; display: flex;flex-direction: column;overflow: hidden;">
				<view style="padding:6px">
					<u-search :clearabled="true" @clickIcon='searchTag' @custom="searchTag" @clear="searchTag" @search='searchTag'
						placeholder="请输入关键字" v-model="tagKeyword"></u-search>
				</view>
				<view style="box-sizing: border-box;flex-grow: 1;padding:10px;overflow-y: auto;">
					<view @click="changeTag(item.code)" class="flex"
						style="justify-content: space-between; line-height: 2.4rem; padding: ; border-bottom: 1px solid #f2f2f2"
						v-for="(item, index) in tagOptions" :key="index">
						<view>
							<view :style="{display: 'inline', color: item.riskColor}">【{{item.riskLabel}}】</view>{{item.name}}
						</view>

						<view v-if="currentTags.indexOf(item.code) >= 0">
							<u-icon name="checkbox-mark" color="#3c9cff"></u-icon>
						</view>
					</view>
				</view>
				<view class="flex" style="box-sizing: border-box;height: max-content; min-height: max-content;padding: 10px;">
					<u-button @click="closedTag" size="small" customStyle="margin-right: 1rem">取消</u-button>
					<u-button @click="submitTag" size="small" type="primary">确定</u-button>
				</view>
			</view>
		</u-popup>


		<u-popup :show="showKnowleage" title="知识库" closeable :round="10" :safeAreaInsetBottom='true' mode="bottom"
			@close="closeKnowleage">
			<view class='knowleagePanel'>
				<view class='knowleageTop'>
					<u-tabs keyName='label' style="width: 100%;" :list="knowledgeTypes" @click="changeKnowledgeTypes"></u-tabs>
				</view>
				<view class='knowleageContent'>
					<view v-if="loadingRecommend">
						<u-loading-icon timing-function="linear" :loading='loadingRecommend'></u-loading-icon>
						<!-- <u-loading-page :loading='loading'></u-loading-page> -->
					</view>
					<template v-else>
						<template v-if="recommend && recommend.length >0">
							<view class="recommendItem">
								<view :key="idx" @click="viewKnowledge(knowledge)" class="knowledgeItem"
									v-for="(knowledge, idx) in recommend">
									<view class="knowledgeTitle" v-html="knowledge.highlightName || knowledge.knowledgeName"></view>
									<view class="knowledgeBaseInfo">
										<view class='flex'>
											<view class='knowledgeLine'>
												<view class="label">作者：</view>
												<view class="value">{{knowledge.knowledgeAuthors || '--'}}</view>
											</view>
											<view class='knowledgeLine' v-if="knowledge.releaseTime">
												<view class="label">发布时间：</view>
												<view class="value">{{$moment(knowledge.releaseTime).format("YYYY-MM-DD HH:mm:ss")}}</view>
											</view>
										</view>
									</view>
									<view class="knowledgeBaseInfo" v-if="knowledge.categorys">
										<view class='knowledgeLine'>
											<view class="label">知识类目：</view>
											<view class="value">{{knowledge.categorys}}</view>
										</view>
									</view>
									<view class="knowledgeDesc">
										<view class='flex'>
											<view class="label">摘要：</view>
											<view class='value' v-html="knowledge.highlightDesc || knowledge.knowledgeDesc"></view>
										</view>
									</view>
									<view class="knowledgeArea" v-if="knowledge.areaNames">
										<view class='flex'>
											<view class="label">适用范围：</view>
											<view>{{knowledge.areaNames}}</view>
										</view>
									</view>
								</view>
							</view>
						</template>
						<view style="text-align: center;color: #999;font-weight: 600;line-height: 4rem;" v-else>暂无推荐</view>
					</template>
				</view>
			</view>
		</u-popup>


		<u-action-sheet :round="10" closeable title="知识库" :show="showKnowledgeDetail" @close='closeKnowleageDetail'>
			<slot>
				<view style="padding-top: 44px; height: 80vh; overflow-y: auto; text-align: left;">
					<knowledge-detail :knowledgeId="currentKnowledge.id" v-if="showKnowledgeDetail" :shareBth="true"
						@shareParams="shareParams"></knowledge-detail>
				</view>
			</slot>
		</u-action-sheet>

		<u-popup :round="10" closeable title="分享" :safeAreaInsetBottom='true' mode="bottom" :show="showShare"
			@close='closeShare'>
			<view  style="padding-top: 44px; height: 80vh; overflow-y: auto; text-align: left;">
				<knowledge-detail v-if="showShare" :knowledgeId.sync="targetId" :shareBth="false"></knowledge-detail>
				<view v-else>无效链接</view>
			</view>
		</u-popup>

		<u-popup :show="showAI" title="AI" closeable :round="10" :safeAreaInsetBottom='true' mode="bottom"
			@close="showAI=false">
			<view style="padding-top: 44px; height: 66vh; overflow-x: hidden; overflow-y: auto;">

			</view>
		</u-popup>

		<u-popup :show="showHistroy" title="历史记录" closeable :round="10" :safeAreaInsetBottom='true' mode="bottom"
			@close="showHistroy=false">
			<view style="padding-top: 44px; height: 66vh;">
				<z-paging class="fullPage" show-refresher-update-time :fixed="false" ref="hisPaging" :auto="false"
					v-model="historyList" @query="queryHisList">
					<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
					<view @click="viewDetail(item)" class="listItem flex" v-for="(item,index) in historyList" :key="index">
						<view style="flex-grow: 1;">
							<view class="listItemName">
								<view class="flex">
									{{item.consultationTypeLabel}}
									<view class="mL6">
										<u-tag :text="distributionTypes[item.distributionType] || '--'" size="mini"></u-tag>
									</view>
								</view>
							</view>
							<view class="listItemInfo">
								<view class="listItemInfoLabel">发起时间：</view>
								<view class="listItemInfoValue">{{item.whenCreated}}</view>
							</view>
							<view class="listItemInfo">
								<view class="listItemInfoLabel">咨询内容：</view>
								<view class="listItemInfoValue">
									{{item.question}}
								</view>
							</view>
						</view>
					</view>
				</z-paging>
			</view>
		</u-popup>

		<u-action-sheet :round='10' :show="showDetailModal" title="咨询详情" @close="()=>{showDetailModal=false;}">
			<slot>
				<view v-if="showDetailModal" style="width: 100%;text-align: left; height: 60vh; overflow-y: auto;">
					<imDetail :consultant='current'></imDetail>
				</view>
			</slot>
		</u-action-sheet>

		<u-popup class='fullPopup' mode='center' closeable :show="showImg" @close="showImg = false">
			<view style='width: 100vw; padding-top: 44px; height: 50vh'>
				<u-swiper imgMode='aspectFit' height='100%' width='100%' :current='currentImg' keyName="url" :list="imageList"
					:autoplay="false" circular></u-swiper>
			</view>
		</u-popup>

		<!-- 发布结束框 -->
		<u-modal :show="showFinish" showCancelButton title="确认结束" content='请确认是否结束当前咨询服务！' @cancel="()=>{showFinish=false}"
			@confirm="confirmFinish"></u-modal>
		<u-safe-bottom></u-safe-bottom>
	</view>
</template>

<script>
	import imDetail from './imDetail.vue';
	import moment from 'moment'
	import {
		toast,
		clearStorageSync,
		getStorageSync,
		useRouter,
		previewImage,
		uploadFile
	} from '@/utils/utils.js'
	import imSupport from '../../utils/imSupport';
	import envParams from '../../api/env';
	export default {
		components: {
			imDetail
		},
		data() {
			return {
				loadingSp: false,
				showShare: false,
				shareUrl: '',
				showAI: false,
				showKnowleage: false,
				showDetailModal: false,
				current: {},
				distributionTypes: {
					system: '系统派单',
					appoint: "管理员指派",
					proac: "律师抢单"
				},
				defaltAva: require('@/static/images/avatar.png'),
				showFinish: false,
				currentImg: 0,
				showImg: false,
				showTags: false,
				showSp: false,
				showHistroy: false,
				top: 0,
				showQuickReplie: false,
				disconnectIM: false,
				showMoreAction: false,
				id: null,
				chartGroup: {},
				dataList: [],
				userInfos: {},
				tagKeyword: '',
				msg: '',
				// 表情数组（如果不需要切换表情面板则不用写）
				emojisArr: ['😊', '😁', '😀', '😃', '😣', '😞', '😩', '😫', '😲', '😟', '😦', '😜', '😳', '😋', '😥', '😰', '🤠',
					'😎', '😇', '😉', '😭', '😈', '😕', '😏', '😘', '😤', '😡', '😅', '😬', '😺', '😻', '😽', '😼', '🙈', '🙉',
					'🙊', '🔥', '👍', '👎', '👌', '✌️', '🙏', '💪', '👻'
				],
				// 当前input focus（如果不需要切换表情面板则不用写）
				focus: false,
				// 当前表情/键盘点击后的切换类型，为空字符串代表展示表情logo但是不展示不展示表情面板（如果不需要切换表情面板则不用写）
				emojiType: '',
				imConfigMap: {},
				quickReplieList: [],
				imageList: [],
				tagOptions: [],
				currentTags: [],
				orgTagOptions: [],
				spData: [],
				midValue: [],
				historyList: [],
				keyWords: [],
				knowledgeTypes: [],
				loadingRecommend: false,
				recommend: [],
				areaCode: '',
				kType: '',
				currentKnowledge: {},
				showKnowledgeDetail: false,
				targetId: null,
				testShare: {
					"shareUrl": "http://127.0.0.1:8082/shareKnowledge?params=eR%2F5rFs4idsCodDiEd27chrv3%2BxhNgc94YfSKfGCPgo%3D",
					"name": "散播疫情相关谣言、故意传播疫情",
					"source": "上海12348涉疫情咨询案例问答汇总（一）（2020年1月24日-2月2日）",
					"remark": "散播疫情相关谣言、故意传播疫情",
					"author": "xxx"
				}
			};
		},
		computed: {
			consultationFinished: function() {
				return this.chartGroup.consultationStatus != 'in_service' ? true : false
			},
			showSendBtn: function() {
				// // #ifndef MP
				// return false
				// // #endif
				// // #ifdef MP
				// return true
				// // #endif
				return true
			},
			imConfig: function() {
				return this.imConfigMap[this.chartGroup.dataSource] || {}
			},
			moreActions: function() {
				let base = [{
					icon: '/static/images/im/tag@3x.png',
					value: 'tag',
					label: '咨询标识'
				}, {
					icon: '/static/images/im/yewuleixing@3x.png',
					value: 'spData',
					label: '业务类型'
				}, {
					icon: '/static/images/im/kuaijiehuifu@3x.png',
					value: 'quickReplie',
					label: '快捷回复'
				}, {
					icon: '/static/images/im/fasongtupian@3x.png',
					value: 'photo',
					label: '发送图片'
				}, {
					icon: '/static/images/im/video@3x.png',
					value: 'video',
					label: '发送视频'
				}]

				if (this.imConfig.intelligentAssistance) {
					base.push({
						icon: '/static/images/im/knowledge@3x.png',
						value: 'knowledge',
						label: '知识库'
					})
					// base.push({
					// 	icon: '/static/images/im/ai@3x.png',
					// 	value: 'ai',
					// 	label: 'AI问答'
					// })
				}

				if (this.imConfig.lawyerShowHistory) {
					base.push({
						icon: '/static/images/im/history@3x.png',
						value: 'history',
						label: '历史记录'
					})
				}

				if (this.imConfig.lawyerCanFinish) {
					base.push({
						icon: '/static/images/im/over@3x.png',
						value: 'finish',
						label: '结束服务'
					})
				}
				return base
			}
		},
		methods: {
			// 知识类别
			getKnowledgeTypes: async function() {
				this.knowledgeTypes = await this.$commonData.getDics(false, {
					category: "KNOWLEDGE_TYPE"
				});
			},
			openKnowleage: function() {
				this.keyWords = []
				this.kType = ''
				this.$api.getKeyWords({
					"groupId": this.chartGroup.groupId
				}).then(res => {
					if (res.success) {
						this.keyWords = res.result || []
					} else {
						toast(res.message)
					}
				}).catch(function(err) {
					console.log('getKeyWords err', err)
					toast('获取咨询关键词失败！')
				}).finally(() => {
					this.showKnowleage = true
					if (this.knowledgeTypes.length > 0) this.changeKnowledgeTypes(this.knowledgeTypes[0])
				})
			},
			closeKnowleage: function() {
				this.showKnowleage = false
				this.keyWords = []
			},
			changeKnowledgeTypes: function(item) {
				console.log('changeKnowledgeTypes', item)
				this.kType = item.val
				this.esSearchKnowledge()
			},
			// 智能推荐搜索
			esSearchKnowledge: function() {
				if (this.keyWords == undefined || this.keyWords == null || this.keyWords.length == 0) {
					return
				}
				let that = this
				this.loadingRecommend = true
				this.recommend = []
				// 默认取前10个
				this.$api.esSearchKnowledge({
					ikSearchs: this.keyWords.map(item => item.name),
					knowledgeType: this.kType,
					areaCode: this.areaCode
				}).then(res => {
					if (res.success) {
						this.recommend = res.result?.list || []
					} else {
						toast(res.message)
					}
				}).catch(function(err) {
					console.log('err', err)
					toast("检索失败！")
				}).finally(() => {
					setTimeout(() => {
						that.loadingRecommend = false
					}, 500)
				})
			},
			viewKnowledge: function(row) {
				this.currentKnowledge = Object.assign({}, row)
				this.showKnowledgeDetail = true
			},
			closeKnowleageDetail: function(row) {
				this.currentKnowledge = {}
				this.showKnowledgeDetail = false
			},
			getShareParams: function(data) {
				try {
					return JSON.parse(data.content)
				} catch (err) {
					console.log('getShareHtml eerr', err)
				}
				return null
			},
			viewShare: function(data) {
				console.log('viewShare', data)
				this.shareUrl = data.shareUrl
				this.targetId = data.targetId

				this.showShare = true

			},
			closeShare: function() {
				this.showShare = false
				this.shareUrl = null
				this.targetId = null
			},
			shareParams: function(data) {
				// this.$emit('shareParams', params)
				console.log('shareParams', data)

				this.showKnowleage = false
				this.showKnowledgeDetail = false

				let shareData = {
					shareUrl: data.shareUrl,
					targetId: data.id,
					typeLabel: data.knowledgeTypeLabel,
					name: data.knowledgeName,
					source: data.knowledgeSource,
					remark: data.knowledgeDesc,
					author: data.knowledgeAuthors
				}
				if (data.knowledgeCover) {
					shareData.cover = data.knowledgeCover
				}
				let chartMessage = {
					sendUserId: this.$commonData.imUserId(),
					messageType: 'TxtMsg',
					groupId: this.chartGroup.groupId,
					messageInfo: {
						extra: 'share',
						content: JSON.stringify(shareData)
					}
				}
				this.messageHandle(chartMessage)
			},
			videoErrorCallback: function(e) {
				console.log('视频错误信息:', e)
				// toast('视频错误')
			},
			viewDetail(item) {
				this.current = item
				this.showDetailModal = true
			},
			searchTag: function() {
				console.log('dd', this.currentTags)
				if (this.tagKeyword) {
					this.tagOptions = this.orgTagOptions.filter(tag => tag.riskLabel.indexOf(this.tagKeyword) >= 0 || tag.name
						.indexOf(this.tagKeyword) >= 0)
				} else {
					this.tagOptions = Object.assign([], this.orgTagOptions)
				}
			},
			getTagOptions: function() {
				this.$api.getTagOptions().then(res => {
					if (res.success) {
						this.orgTagOptions = res.result || []
						this.tagOptions = res.result || []
					} else {
						toast(res.message)
					}
				}).catch(err => {
					console.log('getTagOptions err', err)
					toast("获取咨询标签失败")
				})
			},
			changeTag: function(val) {
				console.log('val', val)
				if (this.currentTags.indexOf(val) >= 0) {
					this.currentTags = this.currentTags.filter(item => item != val)
				} else {
					this.currentTags.push(val)
				}
			},
			closedTag: function() {
				this.showTags = false
				this.currentTags = Object.assign([], this.chartGroup.tags || [])
				this.tagKeyword = ''
				this.searchTag()
			},
			submitTag: function() {
				let params = {
					'id': this.chartGroup.id,
					'tags': this.currentTags
				}
				this.$api.submitTag(params).then(res => {
					if (res.success) {
						toast('操作成功！')
						this.chartGroup = res.result || {}
						this.closedTag()
					} else {
						toast(res.message)
					}
				}).catch(function(err) {
					console.log('submitTag err', err)
					toast('提交标识失败！')
				})
			},
			previewImg: function(item) {
				for (var i = 0; i < this.imageList.length; i++) {
					let data = this.imageList[i]
					if (data.id == item.id) {
						this.currentImg = i
						// previewImage([data.url])
						break
					}
				}
				this.showImg = true
			},
			getAllConfigCacheByType: function() {
				this.$api.getAllConfigCacheByType({
					"schedulingPlanType": "IM"
				}).then(res => {
					if (res.success) {
						this.imConfigMap = res.result || {}
					} else {
						toast(res.message)
					}
				}).catch(function(err) {
					toast("获取配置失败！")
				})
			},
			scrollToBottom() {
				this.top = this.dataList.length * 1000
			},
			formatTime: function(time, format) {
				return moment(time).format(format)
			},
			isMe: function(sendUserId) {
				return sendUserId == this.$commonData.imUserId()
			},
			getDefault: function(sendUserId) {
				let data = this.userInfo(sendUserId, 'consultant')
				if (data) {
					return require('static/images/im/consultant@2x.png')
				} else {
					return require('static/images/im/lawyer@2x.png')
				}
			},
			userInfo: function(sendUserId, key) {
				let data = {}
				if (this.userInfos && sendUserId != 'system_notice') {
					data = this.userInfos[sendUserId] || {}
				}
				return data[key]
			},
			loadChartInfo: function() {
				this.$api.getChartInfo({
					chartId: this.id
				}).then(res => {
					if (res.success) {
						this.chartGroup = res.result || {}
						this.currentTags = Object.assign([], this.chartGroup.tags || [])
						this.queryList()
						let msgMap = uni.getStorageSync('newMsgMap') || {}
						this.$delete(msgMap, this.chartGroup.groupId)
						uni.setStorageSync('newMsgMap', msgMap)
						// this.$nextTick(() => {
						// 	this.$refs.paging.reload(true);
						// })
					} else {
						toast(res.message)
					}
				})
			},
			queryList() {
				// 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				// 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				// 模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					groupId: this.chartGroup.groupId
				}
				this.$api.getIMHistory(params).then(res => {
					if (res.success) {
						let data = res.result || {}
						this.userInfos = data.userInfos || {}
						// 将请求的结果数组传递给z-paging
						let list = data.hisMessages || []
						list.forEach(item => {
							if (item.messageExtra == 'share') {
								item.messageInfo.params = this.getShareParams(item.messageInfo)
							} else {
								this.previewImageList(item.id, item.messageType, item.messageInfo)
							}
						})

						this.dataList = list
						// messages.reverse()
						// this.$refs.paging.setLocalPaging(messages);

					} else {
						// this.$refs.paging.complete(false);
						toast(res.message)
					}

				}).catch(res => {
					// 如果请求失败写this.$refs.paging.complete(false);
					// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
					// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
					// this.$refs.paging.complete(false);
				}).finally(() => {
					this.scrollToBottom()
				})
			},
			quickReplies: function() {
				this.$api.quickReplies().then(res => {
					if (res.success) {
						this.quickReplieList = res.result || []
						this.quickReplieList.forEach(item => item.name = item.message)
					} else {
						toast(res.message)
					}
				}).catch(err => {
					console.log('quickReplies err', err)
				})
			},
			// 更新了键盘高度（如果不需要切换表情面板则不用写）
			keyboardHeightChange(res) {
				if (res.height > 0) {
					// 键盘展开，将emojiType设置为emoji
					this.emojiType = 'emoji';
				}
			},
			// 用户尝试隐藏键盘，此时如果表情面板在展示中，应当隐藏表情面板，如果是键盘在展示中不用处理，z-paging内部已经处理（如果不需要切换表情面板则不用写）
			hidedKeyboard() {
				if (this.emojiType === 'keyboard') {
					this.emojiType = '';
				}
			},
			// 点击了切换表情面板/键盘（如果不需要切换表情面板则不用写）
			emojiChange() {
				this.$emit('emojiTypeChange', this.emojiType);
				this.showMoreAction = false
				if (this.emojiType === 'keyboard') {
					// 点击了键盘，展示键盘
					this.focus = true;
					try {
						uni.showKeyboard()
					} catch (err) {}
				} else {
					// 点击了切换表情面板
					this.focus = false;
					// 隐藏键盘
					try {
						uni.hideKeyboard();
					} catch (err) {}
				}
				this.emojiType = (!this.emojiType || this.emojiType === 'emoji') ? 'keyboard' : 'emoji';
			},
			// 点击了某个表情，将其插入输入内容中（如果不需要切换表情面板则不用写）
			emojiClick(text) {
				this.msg += text;
			},
			moreAction: function() {
				this.emojiType = '';
				this.showMoreAction = !this.showMoreAction
			},
			actionClick: function(item) {
				let that = this
				this.showMoreAction = false
				switch (item.value) {
					case 'tag':
						//咨询标识
						this.showTags = true
						break
					case 'spData':
						//业务类型
						if (this.spData.length == 0) {
							this.initSpData()
						}
						this.showSp = true
						break
					case 'quickReplie':
						//快捷回复
						this.showQuickReplie = true
						break
					case 'photo':
						//发送图片 https://doc.dcloud.net.cn/uni-app-x/api/choose-image.html
						this.sendImg()
						break
					case 'video':
						//发送视频
						this.sendVideo()
						break
					case 'knowledge':
						//知识库
						this.openKnowleage()
						break
					case 'ai':
						//AI问答
						this.showAI = true
						break
					case 'history':
						//历史记录
						this.showHistroy = true
						this.$nextTick(() => {
							this.$refs.hisPaging.reload(true);
						})
						break
					case 'finish':
						//结束服务
						this.showFinish = true
						break
				}
			},
			sendImg: function() {
				let that = this
				let fileSize = this.$systemConfig.fileSize || 10
				uni.chooseImage({
					count: 1, //最多可以选择的图片张数 默认9，app端不限制，微信小程序最多可支持20个。
					success: function(op) {
						console.log('po', op)
						if (op.errMsg == 'chooseImage:ok') {
							op.tempFiles.forEach(tempFile => {
								op.tempFiles.forEach(tempFile => {
									if (tempFile.size > fileSize * 1024 * 1024) {
										toast(`图片大于${fileSize}MB，不予上传！`)
									} else {
										uploadFile(tempFile).then(item => {
											console.log('uploadFile', item)
											let chartMessage = {
												sendUserId: that.$commonData.imUserId(),
												messageType: 'ImgMsg',
												groupId: that.chartGroup.groupId,
												messageInfo: {
													extra: 'auto',
													content: item.originalName,
													localPath: item.url,
													imageUri: item.url
												}
											}
											that.messageHandle(chartMessage)
										}).catch(err => {
											console.log('uploadFile err', err)
											toast('图片发送失败！')
										})
									}
								})
							})
						} else {
							toast(op.errMsg)
						}
					},
					fail(err) {
						console.log('fail', err)
						toast('图片上传失败！')
					}
				})
			},
			sendVideo: function() {
				let that = this
				let fileSize = this.$systemConfig.fileSize || 10
				uni.chooseVideo({
					success: function(op) {
						console.log('po', op)
						if (op.errMsg == 'chooseVideo:ok') {
							let tempFile = {
								path: op.tempFilePath,
								height: op.height,
								width: op.width,
								size: op.size,
								name: op.name
							}
							if (tempFile.size > fileSize * 1024 * 1024) {
								toast(`视频大于${fileSize}MB，不予上传！`)
							} else {
								uploadFile(tempFile).then(item => {
									console.log('uploadFile', item)
									let chartMessage = {
										sendUserId: that.$commonData.imUserId(),
										messageType: 'SightMsg',
										groupId: that.chartGroup.groupId,
										messageInfo: {
											extra: 'auto',
											duration: op.duration,
											name: op.name,
											size: op.size,
											content: item.originalName,
											sightUrl: item.url
										}
									}
									that.messageHandle(chartMessage)
								}).catch(err => {
									console.log('uploadFile err', err)
									toast('视频发送失败！')
								})
							}
						} else {
							toast(op.errMsg)
						}
					},
					fail(err) {
						console.log('fail', err)
						toast('文件上传失败！')
					}
				})
			},
			closeSp: function() {
				this.midValue = []
				this.showSp = false
			},
			changeData: function(value) {
				console.log('changeData', value)
				this.midValue = value
				this.submitSp()
			},
			submitSp: function() {
				if (this.midValue && this.midValue.length > 0) {
					let dicSpecialtyIds = this.midValue.map(item => item.value)
					let param = {
						id: this.chartGroup.id,
						dicSpecialtyIds: dicSpecialtyIds
					}
					this.$api.modifyDicSpecialty(param).then(res => {
						if (res.success) {
							toast('修改成功！')
							this.chartGroup.dicSpecialtyIds = dicSpecialtyIds
							this.closeSp()
						} else {
							toast(res.message)
						}
					}).catch(function(err) {
						console.log('modifyDicSpecialty error', err)
						toast('修改业务类型失败！')
					})
				} else {
					toast('请选择业务类型！')
				}
			},
			queryHisList: function(pageNo, pageSize) {
				let that = this
				const params = {
					pageNo: pageNo,
					pageSize: pageSize,
					promoterId: this.chartGroup.promoterId
				}

				this.$api.findConsultantHisChart(params).then(res => {
					if (res.success) {
						this.$refs.hisPaging.complete(res.result.data || []);
					} else {
						toast(res.message)
						this.$refs.hisPaging.complete(false);
					}
				}).catch(function(err) {
					console.log('getImConsultions', err)
					toast("获取即时咨询历史失败！")
					this.$refs.hisPaging.complete(false);
				})
			},
			confirmFinish: function() {
				let that = this
				this.$api.finishService({
					groupId: this.chartGroup.groupId
				}).then(res => {
					if (res.success) {
						that.finishOp()
					} else {
						toast(res.message)
					}
				}).catch(function(err) {
					console.log(err)
					toast("结束失败！")
				}).finally(() => {
					this.showFinish = false
				})
			},
			// todo 保存图片
			saveImage() {
				uni.saveImageToPhotosAlbum({
					filePath: "/static/uni.png",
					success: (res) => {
						console.log("saveImageToPhotosAlbum success", JSON.stringify(res));
						uni.showToast({
							position: "center",
							icon: "none",
							title: "图片保存成功，请到手机相册查看"
						});
						this.success = true;
					},
					fail: (err) => {
						uni.showModal({
							title: "保存图片到相册失败",
							content: JSON.stringify(err),
							showCancel: false
						});
						this.success = false;
					}
				})
			},
			finishOp: function() {
				this.$set(this.chartGroup, 'consultationStatus', 'finish')
				toast("当前咨询已结束，3秒后返回咨询列表！")
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/consultant/consultant'
					})
				}, 3000)
			},
			selectQuickReplie: function(item) {
				console.log('selectQuickReplie', item)
				this.showQuickReplie = false
				let chartMessage = {
					sendUserId: this.$commonData.imUserId(),
					messageType: 'TxtMsg',
					groupId: this.chartGroup.groupId,
					messageInfo: {
						extra: item.messageExtra || 'auto',
						content: item.message
					}
				}
				this.messageHandle(chartMessage)
			},
			uploadImg: function(item) {
				let chartMessage = {
					sendUserId: this.$commonData.imUserId(),
					messageType: 'ImgMsg',
					groupId: this.chartGroup.groupId,
					messageInfo: {
						extra: 'auto',
						content: item.name,
						localPath: item.url,
						imageUri: item.url
					}
				}
				this.messageHandle(chartMessage)
			},
			uploadVedio: function(item) {
				let chartMessage = {
					sendUserId: this.$commonData.imUserId(),
					messageType: 'SightMsg',
					groupId: this.chartGroup.groupId,
					messageInfo: {
						extra: 'auto',
						name: item.name,
						content: item.name,
						duration: 120,
						sightUrl: item.url
					}
				}
				this.messageHandle(chartMessage)
			},
			// 点击了发送按钮
			sendMessage: function() {
				if (this.msg == undefined || this.msg == null || this.msg.trim() == '') return
				let chartMessage = {
					sendUserId: this.$commonData.imUserId(),
					messageType: 'TxtMsg',
					groupId: this.chartGroup.groupId,
					messageInfo: {
						extra: 'auto',
						content: this.msg || ''
					}
				}
				this.messageHandle(chartMessage)
			},
			messageHandle: function(chartMessage) {
				let that = this
				uni.showLoading({
					title: '发送中...'
				})
				that.$api.sendMessage(chartMessage).then(res => {
					if (res.success) {
						this.msg = ''
					} else {
						toast(res.message)
					}
				}).catch(function(err) {
					console.log(err)
					toast("消息发送失败！")
				}).finally(() => {
					uni.hideLoading()
				})
			},
			messageBlur: function() {
				console.log('messageBlur')
				this.focus = false
				// 只给咨询人发送律师状态消息
				imSupport.sendDirectMessage({
					// 文本内容
					content: '律师停止输入',
					// （可选）消息中附加信息，透传到对端
					extra: 'writeStop',
				}, 'TxtMsg', this.chartGroup.groupId, [this.chartGroup.promoterId])
			},
			messageFocus: function() {
				console.log('messageBlur')
				this.focus = true
				// 只给咨询人发送律师状态消息
				imSupport.sendDirectMessage({
					// 文本内容
					content: '律师输入中...',
					// （可选）消息中附加信息，透传到对端
					extra: 'writerProcessing',
				}, 'TxtMsg', this.chartGroup.groupId, [this.chartGroup.promoterId])
			},
			previewImageList: function(id, messageType, messageInfo) {
				switch (messageType) {
					case 'GIFMsg':
						this.imageList.push({
							id: id,
							url: messageInfo.remoteUrl
						})
						break
					case 'ImgMsg':
						this.imageList.push({
							id: id,
							url: messageInfo.imageUri
						})
						break
					case 'SightMsg':
						this.imageList.push({
							id: id,
							url: messageInfo.sightUrl
						})
						break
				}
				console.log('this.imageList', this.imageList)
			},
			// 监听键盘高度改变，请不要直接通过uni.onKeyboardHeightChange监听，否则可能导致z-paging内置的键盘高度改变监听失效（如果不需要切换表情面板则不用写）
			receiveMsg: function(item) {
				let extra = item.content ? item.content.extra : 'auto'
				let messageType = item.messageType.replace('RC:', '');
				console.log(extra, messageType)
				if (item.targetId == this.chartGroup.groupId) {
					let msgMap = uni.getStorageSync('newMsgMap') || {}
					this.$delete(msgMap, this.chartGroup.groupId)
					uni.setStorageSync('newMsgMap', msgMap)
					let messageInfo = item.content
					if (extra == 'share') {
						messageInfo.params = this.getShareParams(item.content)
					}
					console.log('messageInfo', messageInfo)
					this.dataList.push({
						groupId: item.targetId,
						sendUserId: item.senderUserId,
						messageType: messageType,
						messageInfo: messageInfo,
						messageExtra: extra
					})
					this.previewImageList(item.messageUId, messageType, messageInfo)
					switch (extra) {
						case 'finish':
							//关闭
							this.finishOp()
							break
					}
					this.$nextTick(() => {
						this.scrollToBottom()
					})
				}
			},
			initSpData: function() {
				this.loadingSp = true;
				this.$api.spFullTree().then(res => {
					if (res.success) {
						this.spData = res.result || []
					} else {
						toast(res.message)
					}
				}).catch(err => {
					console.log('initSpData err', err)
				}).finally(() => {
					this.loadingSp = false;
				})
			}
		},
		onLoad(query) {
			console.log('onLoad', query)
			let that = this

			if (query.id) {
				this.id = query.id
				this.getKnowledgeTypes()
				this.getTagOptions()
				this.quickReplies()
				this.getAllConfigCacheByType()
				this.loadChartInfo()

				uni.$off('chartMsg')
				uni.$off('changeIMStatus')

				uni.$on('chartMsg', function(message) {
					console.log('chartMsg ，携带参数为：' + message);
					that.receiveMsg(message)
				})

				uni.$on('changeIMStatus', function(status) {
					console.log('changeIMStatus ，携带参数为：' + status);
					that.disconnectIM = status == 'offline' ? true : false
				})
			} else {
				toast('未知当前聊天室信息！')
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/consultant/consultant'
					})
				}, 1000)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {

		// mp 安全区域设置
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.chartContainer {
			height: 100%;
			display: flex;
			flex-direction: column;
			overflow: hidden;
		}

		.chatInfo {
			flex-grow: 1;
			overflow: hidden;
			display: flex;
			flex-direction: column;

			.scroll-view {
				flex-grow: 1;
				overflow: hidden;
			}


		}

		.chat-input-bar-container {
			box-sizing: border-box;
			width: 100%;
			background-color: #f8f8f8;



			.chat-input-bar {
				padding: 5px;
				display: flex;
				overflow: hidden;
				justify-content: space-between;
			}
		}

		.header {
			background-color: red;
			font-size: 24rpx;
			text-align: center;
			padding: 20rpx 0rpx;
			color: white;
		}

		.chat-item {
			display: flex;
			flex-direction: column;
			padding: 20rpx;
			overflow: hidden;
		}

		.chat-time {
			padding: 4rpx 0rpx;
			text-align: center;
			font-size: 22rpx;
			color: #aaaaaa;
		}

		.chat-tipInfo {
			padding: 4rpx 0rpx;
			text-align: center;
			font-size: 24rpx;
			color: #666;
		}

		.chat-container {
			display: flex;
			flex-direction: row;
			overflow: hidden;
		}

		.chat-location-me {
			flex-direction: row-reverse;
			text-align: right;
		}

		.chat-icon-container {
			margin-top: 12rpx;
		}

		.chat-icon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			background-color: #eeeeee;
		}

		.chat-content-container {
			margin: 0rpx 10px;
		}

		.chat-user-name {
			font-size: 26rpx;
			color: #888888;
		}

		.chat-text-container {
			text-align: left;
			background-color: #fff;
			border-radius: 8rpx;
			padding: 10rpx 15rpx;
			margin-top: 10rpx;
			max-width: 70vw;
			position: relative;
			overflow: hidden;
			box-sizing: border-box;
		}

		.chat-text-container::before {
			content: "";
			position: absolute;
			left: -6px;
			top: 8px;
			border-top: 8px solid transparent;
			border-right: 8px solid #fff;
			border-bottom: 8px solid transparent;
		}

		.chat-text-container-me {
			background-color: #007AFF;
		}

		.chat-text-container-me::before {
			content: none;
		}

		.chat-text-container-me::after {
			content: "";
			position: absolute;
			right: -6px;
			top: 8px;
			border-top: 8px solid transparent;
			border-left: 8px solid #007AFF;
			border-bottom: 8px solid transparent;
		}

		.chat-text-container-super {
			display: flex;
			flex-direction: row;
		}

		.chat-text {
			font-size: 28rpx;
			box-sizing: border-box;
			word-break: break-all;
			overflow: hidden;
		}

		.chat-text-me {
			color: white;
		}

		.content .chat-input-bar {
			display: flex;
			flex-direction: row;
			align-items: center;
			border-top: solid 1px #f5f5f5;
			background-color: #f8f8f8;

			padding: 10rpx 20rpx;
		}

		.chat-input-container {
			flex: 1;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			// padding: 15rpx;
			background-color: white;
			border-radius: 10rpx;
			max-height: 20vh;
			overflow: auto;
		}

		.chat-input {
			flex: 1;
			font-size: 28rpx;
		}

		.btn-container {
			display: flex;
			align-items: center;
			margin-left: 5px;
		}

		.emoji-img {
			width: 54rpx;
			height: 54rpx;
			margin: 0 5px;
		}

		.chat-input-send {
			background-color: #007AFF;
			margin: 5px;
			border-radius: 10rpx;
			// width: 110rpx;
			// height: 60rpx;
			padding: 0 8px;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			justify-content: center;
			align-items: center;
		}

		.chat-input-send-text {
			color: white;
			font-size: 26rpx;
		}

		.action-panel-container {
			background-color: #f8f8f8;
			overflow: hidden;
			transition-property: height;
			transition-duration: 0.15s;
			/* #ifndef APP-NVUE */
			will-change: height;
			/* #endif */
		}

		.action-panel {
			font-size: 30rpx;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
			flex-wrap: wrap;
			padding-right: 10rpx;
			padding-left: 15rpx;
			padding-bottom: 10rpx;
		}

		.action-item {
			width: 25%;
			text-align: center;
			box-sizing: border-box;
			padding: 8px 0;
		}

		.action-item-centent {
			background: #fff;
			border-radius: 12px;
			width: 60px;
			height: 60px;
			margin: auto;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.action-item-label {
			color: $uni-color-subtitle;
			font-size: 12px;
			margin-top: 6px;
		}

		.action-panel-text {
			font-size: 50rpx;
			margin-left: 15rpx;
			margin-top: 20rpx;
		}

		.knowleagePanel {
			padding-top: 44px;
			height: 80vh;
			overflow: hidden;
			display: flex;
			flex-direction: column;

			.knowleageContent {
				flex-grow: 1;
				overflow-y: auto;
				padding: 10px;
				box-sizing: border-box;

				.knowledgeItem {
					padding: 6px;
					background: #fff;
					border: 1px solid #2781ee;
					margin-bottom: 10px;
					border-radius: 5px;
					cursor: pointer;

					.knowledgeTitle {
						font-weight: 500;
						// line-height: 1.6rem;
						font-size: 0.84rem;
						border-bottom: 1px solid #2781ee;
						margin-bottom: 4px;
						padding-bottom: 4px;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.knowledgeLine {
						display: flex;

					}

					.knowledgeBaseInfo {
						display: flex;
						color: #999;
						font-size: 12px;
						overflow: hidden;


						// flex-wrap: wrap;
						// margin-bottom: 10px;
						// border-bottom: 1px dashed #ddd;

						.label {
							white-space: nowrap;
							width: fit-content;
							min-width: max-content;
						}

						.value {
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
						}
					}

					.knowledgeContent {
						color: #666;
						font-size: 0.8rem;
					}

					.knowledgeDesc {
						color: #666;
						font-size: 0.8rem;
						margin: 4px 0;
					}

					.knowledgeArea {
						color: #a4a4a4;
						font-size: 12px;
						border-top: 1px dotted #eee;
					}
				}

				.knowledgeItem:hover {
					background: #eff5ff;
					border: 1px solid #2781ee;

					.knowledgeTitle {
						border-bottom: 1px solid #2781ee;
					}
				}
			}
		}



	}

	.fullPage {
		height: 100%;
		background-color: $uni-main-color;
	}
</style>